package com.nexgo.payment.action.scan;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.nexgo.payment.R;
import com.nexgo.payment.action.Action;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.ui.BaseFragment;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.payment.util.UIUtils;
import com.nexgo.payment.widget.ScanCodeTextWatcher;
import com.nexgo.payment.widget.TitleBuilder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import java8.util.Optional;

/**
 * 创建日期:2018/1/16 16:35
 * 创建人： wzp
 * @version
 * 修改人： wzp
 * 类说明;
 */
public class BccScanFragment extends BaseFragment implements Action<ActionStep>, BccScanContract.View,BaseFragment.DownTimerListener{
//public class BccScanFragment extends AbsTransActivity<BccScanContract.Presenter> implements Action<ActionStep>, BccScanContract.View {

    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.tv_prompt_scan)
    TextView tvPromptScan;
    @BindView(R.id.edt_scan_code)
    EditText edtScanCode;
    @BindView(R.id.iv_alipay)
    ImageView ivAlipay;
    @BindView(R.id.iv_unionpay)
    ImageView ivUnionpay;
    @BindView(R.id.iv_wechatpay)
    ImageView ivWechatpay;
    @BindView(R.id.iv_scan)
    ImageView iv_scan;
    @BindView(R.id.btn_confirm)
    Button btnConfirm;
    @BindView(R.id.tv_amount_scan)
    TextView tvAmountTip;
    @BindView(R.id.title_tv_right)
    TextView tvTitleRight;

    private static final String TRANS_DATA = "trans_data";
    private BccScanContract.Presenter mPresenter;
    private OnActionListener mListener;
    private Unbinder unbinder;
    private Logger mLog = LoggerFactory.getLogger(BccScanFragment.class.getSimpleName());

    public BccScanFragment() {
    }

    public static BccScanFragment newInstance(TransData transData) {
        BccScanFragment fragment = new BccScanFragment();
        Bundle args = new Bundle();
        args.putParcelable(TRANS_DATA, transData);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TransData transData = null;
        if (getArguments() != null) {
            transData = getArguments().getParcelable(TRANS_DATA);
        }
/*        //强制屏幕常亮
        Window win = getActivity().getWindow();
        win.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //屏蔽菜单键
        win.addFlags(5);
        //屏蔽home键
        win.addFlags(3);
        //屏蔽下拉
        Settings.System.putInt(getContext().getContentResolver(), "status_bar_disabled", 1);*/
        new BccScanPresenter(this, Repository.getInstance(),transData);

    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_bcc_scan, container, false);
        unbinder = ButterKnife.bind(this, view);

        initTitle(view);

        return view;
    }

    //初始化标题栏
    private void initTitle(View view) {
        new TitleBuilder(view)
                .setExternalTitleBgRes(R.drawable.bg_blue_icon)
                .setTitleText(getString(R.string.scan_sale_start))
                .build();
    }

    @OnClick({R.id.title_iv_left,R.id.iv_scan})
    public void onClick(View view){
        if (UIUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.title_iv_left:
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(this, ActionResult.ERR_CANCEL, null));
                }
                break;
            case R.id.iv_scan: //调扫码
                mPresenter.onStartScanner();
                break;
            default:
                break;
        }
    }
    @Override
    protected void initEvent() {
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.start();
        //第一次调用不起作用，扫码返回后再次调用才起作用
        mPresenter.showOnScanNextAndRestart();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnActionListener) {
            mListener = (OnActionListener) context;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        mPresenter.destroy();
    }

    @Override
    public ActionStep getActionStep() {
        return ActionStep.INPUT_SCAN;
    }


    @Override
    public void showAmount(String amount) {
        tvAmountTip.setVisibility(View.VISIBLE);
        String format = SysConstant.FUND_SYMBOL + StringUtils.formatAmount(amount, SysConstant.FUND_DIGITS);
        tvAmount.setText(format);
        tvAmount.setVisibility(View.VISIBLE);
    }

    @Override
    public void showErrMsg(String message) {
        Optional.ofNullable(message)
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> ToastUtils.showToast(s));
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.ERR_CANCEL, message));
        }
    }

    @Override
    public void showScanSuccessful(HashMap<String, String> data) {
        if (mListener != null) {
            mLog.debug("showScanSuccessful");
            mListener.setActionResult(new ActionResult(this, ActionResult.SUCC, data));
        }
        mPresenter.onStopScanner();
        cancelDownTimer();
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    public void showCountTime(int countTime) {
        setDownTimer(countTime + 1, this);
    }

    @Override
    public void showScanCode() {
        tvAmountTip.setVisibility(View.VISIBLE);
        ivAlipay.setVisibility(View.VISIBLE);
        ivWechatpay.setVisibility(View.VISIBLE);
        ivUnionpay.setVisibility(View.VISIBLE);
        iv_scan.setVisibility(View.VISIBLE);
        tvPromptScan.setText("请扫码或手输付款码");
        edtScanCode.setVisibility(View.VISIBLE);
        btnConfirm.setVisibility(View.VISIBLE);
        btnConfirm.setBackgroundResource(R.drawable.gray_button);
        edtScanCode.addTextChangedListener(new ScanCodeTextWatcher(edtScanCode) {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                if (s.length() >= 15 && s.length() <= 30) {
                    mLog.debug("onTextChanged true {}" ,s);
                    btnConfirm.setEnabled(true);
                    btnConfirm.setBackgroundResource(R.drawable.btn_confirm);
                } else {
                    mLog.debug("onTextChanged false {}",s);
                    btnConfirm.setEnabled(false);
                }
            }
        });
        mLog.debug("showScanCode");
        btnConfirm.setOnClickListener(v -> mPresenter.importScanCode(edtScanCode.getText().toString()));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        cancelDownTimer();
        unbinder.unbind();
        mPresenter.destroy();
    }


    @Override
    public void setPresenter(BccScanContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void onTick(long secondsUntilFinished) {
        if (!isActive()) {
            return;
        }
        tvTitleRight.setVisibility(View.VISIBLE);
        tvTitleRight.setText(String.valueOf(secondsUntilFinished));
    }

    @Override
    public void onFinish() {
        if (isActive()) {
            tvTitleRight.setText("0");
        }
    }
}
